<?
require_once("mvc/action/Action.php");
require_once("cms/core/om/BinaryFile.php");

class SaveAction extends Action {

    private $log;

    public function __construct() {
        $this->log =& LoggerManager::getLogger("SaveAction");
    }

    public function execute(ActionConfig &$mapping, &$form, Request &$request, Response &$response) {

        $errors = new ActionMessages();

        $revision = $form->getRevision();
        $revision->setLatest(true);
        $revision->setInsertDate(date(_Core::FORMAT_SQLDATETIME));

        $download = $revision->getDownload();

        if($form->getPublicationYear() == "" || $form->getPublicationMonth() == "" || $form->getPublicationDay() == "") {
            $download->setPublicationDate("0000-00-00");
            $download->setPublicationDate(null);
        } else {
            $download->setPublicationDate(
                $form->getPublicationYear()."-".
                $form->getPublicationMonth()."-".
                $form->getPublicationDay()
            );
        }

        $formFile =& $form->getFormFile();

        $conn = Propel::getConnection();

        try {

            $conn->begin();

            // process image
            $formImage =& $form->getFormImage();
            
            if(!$form->getDeleteImage() && $formImage["size"] > 0) {

                $image = $download->getImageRelatedByImageId();
                $thumb = $download->getImageRelatedByThumbnailId();

                require_once("cms/core/util/ImageProperties.php");
                $properties = new ImageProperties(
                    $request->getContext()->getInitParameter(_Core::SETTING_LIST)
                );

                require_once("cms/core/util/ImageProcessor.php");
                ImageProcessor::process(
                    $conn, $errors, $formImage,
                    $properties, $image, $thumb
                );

                // Set the generated ids
                $download->setThumbnailId($thumb->getImageId());
                $download->setImageId($image->getImageId());

            } else if($form->getDeleteImage()) {

                $image = $download->getImageRelatedByImageId();
                $thumb = $download->getImageRelatedByThumbnailId();

                require_once("cms/core/om/BinaryFilePeer.php");

                BinaryFilePeer::doDelete($thumb->getBinaryFile(), $conn);
                BinaryFilePeer::doDelete($image->getBinaryFile(), $conn);
            }

            if($revision->getDownloadRevisionId() > 0) {

                $download->setDownloadId($revision->getDownloadId());

                // Update the download
                DownloadPeer::doUpdate($download, $conn);

                // update the NULL revision to the latest one.
                if($formFile["size"] > 0) {

                    // No Revisioning !!
                    if($form->getOverwrite() == "true") {

                        // update file
                        if($formFile["size"] > 0) {
                            $binaryFile = new BinaryFile();
                            $binaryFile->setBinaryFileId($revision->getBinaryFileId());
                            $binaryFile->saveForm($formFile, $conn);
                        }

                        DownloadRevisionPeer::doUpdate($revision, $conn);

                    } else {

                        // insert file
                        if($formFile["size"] > 0) {
                            $binaryFile = new BinaryFile();
                            $binaryFile->saveForm($formFile, $conn);
                            $revision->setBinaryFileId($binaryFile->getBinaryFileId());
                        }

                        $sql = "SELECT max(revision) as max from download_revision ".
                               "WHERE download_revision.download_id = '". mysql_real_escape_string($revision->getDownloadId()) . "'";
                        $stmt = $conn->prepareStatement($sql);
                        $rs = $stmt->executeQuery(ResultSet::FETCHMODE_NUM, $conn);

                        $max = 0;
                        if($rs->next())
                            $max = $rs->getInt("max");

                        $sql = "UPDATE download_revision SET latest = 0 " .
                               "WHERE download_revision.latest = 1 AND download_id = '".mysql_real_escape_string($revision->getDownloadId())."' LIMIT 1";
                        $stmt = $conn->prepareStatement($sql);
                        $rs = $stmt->executeQuery(ResultSet::FETCHMODE_NUM, $conn);

                        $revision->setRevision($max + 1);

                        // insert new revision.
                        DownloadRevisionPeer::doInsert($revision, $conn);

                    }
                }


            } else {

                // insert file
                if($formFile["size"] > 0) {
                    $binaryFile = new BinaryFile();
                    $binaryFile->saveForm($formFile, $conn);
                    $revision->setBinaryFileId($binaryFile->getBinaryFileId());
                }

                $download->setActive(_Core::AUTO_ACTIVATE);
                $download->setPosition($download->getMaxPosition() + 1);

                $revision->setDownloadId(
                    DownloadPeer::doInsert($download, $conn)
                );
                $revision->setRevision(1);
                // insert new revision.
                DownloadRevisionPeer::doInsert($revision, $conn);

            }

            $conn->commit();

        } catch(PropelException $e) {
            $conn->rollback();
            $errors->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("error.save", true));
            $this->log->error($e->getMessage());
        }

        // Return any save errors.
        if(!$errors->isEmpty()) {
            $this->saveErrors($request, $errors);
            return $mapping->getInputForward();
        }


        // Reset the downloadListForm from & to session.
        $session  = $request->getSession();
        $listForm = $session->getAttribute("cms/downloadListForm");
        if(!is_null($listForm)) {
            $listForm->setPage(1);
            $session->setAttribute("cms/downloadListForm", $listForm);
        }


        // To the success download.
        return $mapping->findForward("success");


    }

}
?>